<?php
namespace app\mobile\controller;

use think\Db;
use think\Request;
use think\Session;
use app\mobile\model\Config;
use app\mobile\model\Limited;
use app\mobile\model\ShopGoods;
use app\mobile\model\GroupGoods;
use app\mobile\model\LimitedType;
use app\mobile\model\ShopSpecAttr;
use app\mobile\model\MemberCollect;
use app\mobile\model\MemberShoppingCart;
use app\mobile\model\TemporaryShoppingCart;
use app\mobile\controller\UserPort as UserPortController;

/**
 * Class UserCart
 * @package app\mobile\controller   购物车
 */
class UserCart extends BaseController
{
    /*
     * 购物车首页
     */
    public function cart_index()
    {
        // 搜索条件
        $condition['state'] = ['eq', 1];
        $condition['activity'] = ['eq',2];


        $user_port = new UserPortController();

        $result = $user_port->guess_like();

        // // 是否开启审核
        // if ($config->where('varname','web_commodity_audit')->value('varvalue') == 'Y') $condition['status'] = ['eq', '1'];
        //
        // // 是否开启猜你喜欢
        // if ($config->where('varname','web_related')->value('varvalue') == 'Y') {
        //
        //     $condition['related'] = ['eq', 1];
        //
        //     $result = ShopGoods::where($condition)->field('id,title,price,thumb_img,sale_number,rebate_percentage')
        //         ->limit('4')->order(['shop_sort' => 'desc', 'sort' => 'desc', 'create_time' => 'desc'])
        //         ->select();
        //
        // } else {
        //
        //     // 查询商品ID
        //     $result = ShopGoods::where($condition)->field('id,title,price,thumb_img,sale_number,rebate_percentage')
        //         ->limit('4')->order(['rand()' => 'desc'])->select();
        //
        // }
        //购物车列表
        $data = $this->cart_list();


        return $this->fetch('',[
            'likeArr'       =>      $result,
            'data'          =>      $data,
        ]);
    }


    public function shiyi()
    {
        //查询会员购物车内商品
        $model = new MemberShoppingCart();
        $data = $model
            ->where('sun_member_shopping_cart.member_id',Session::get('member_id'))
            ->with(['shopGoods1'=>function($e){
                $e
                    ->withField('id,member_id,rebate_percentage,thumb_img,title,freight,status')->where('status',1);
            }])
            ->select();

        $opt = [];
        if ($data){
            //合并同一店铺商品
            foreach ($data as $v){

                if ($v['shop_goods1']!=null) {
                    $v->shopGoods->shop;
                    $opt[$v->shopGoods->shop->title][] = $v;
                }

            }
        }

        // return $opt;

        return json($opt);
    }
    /*
     * 购物车列表
     */
    public function cart_list()
    {
        //查询会员购物车内商品
        $model = new MemberShoppingCart();
        $data = $model->where('sun_member_shopping_cart.member_id',Session::get('member_id'))
            ->with(['shopGoods'=>function($e){
                $e->withField('id,member_id,rebate_percentage,thumb_img,title,freight,status');
            }])->order('id','desc')->select();

        $opt = [];
        if ($data){
            //合并同一店铺商品
            foreach ($data as $v){
                $v->shopGoods->shop;
                $opt[$v->shopGoods->shop->title][] = $v;
            }
        }

        return $opt;
    }
    /*
     * 查询商品库存
     */
    public function query_inventory(Request $request)
    {
        if ($request->isPost()){
            $goods_id = $request->post('id');
            $cart_id = $request->post('cart_id');
            $num = $request->post('num');

            $attr = $request->post('attr');
            $inventory = (new ShopGoods())->where('id',$goods_id)->value('inventory');

            //有属性
            if ($attr){
                $attr_inventory = (new ShopSpecAttr())->where(['goods_id' => $goods_id , 'attribute' => $attr])->value('inventory');

                if ($attr_inventory){
                    $inventory = $attr_inventory;
                }else{
                    $inventory = $inventory ;
                }
            }
            if ($num >= $inventory){

                return ['code'=>400,'message'=>'商品库存数量不足'];
            }else{
                (new MemberShoppingCart())->where('id',$cart_id)->setInc('number');
                return ['code'=>200];
            }
        }
    }
    /*
     * 查询商品是否为限购商品
     */
    public function query_limited(Request $request)
    {
        if ($request->isPost()){
            $id = $request->post('id');
            $limited = (new MemberShoppingCart())->where('id',$id)->value('limited_status');
            return $limited;
        }
    }
    /*
     * 默认购物车添加
     */
    public function default_cart(Request $request)
    {
        if ($request->isPost()){
            if (!Session::has('member_id')){return ['code'=>401,'message'=>'您还未登录,请登录'];}

            //检测商品库存(无属性总库存)
            $inventory = (new ShopGoods())->where(['id' => $request->post('id')])->value('inventory');

            //有属性库存
            if ($request->post('attr')){
                $attr_inventory = (new ShopSpecAttr())->where(['goods_id' => $request->post('id'), 'attribute' => $request->post('attr')])->value('inventory');

                if (!$attr_inventory){
                    $inventory = 0;
                }else{
                    $inventory = $attr_inventory;
                }
            }

            if ($request->post('num') > $inventory){
                return ['code' => 0,'message' => '库存不足,剩余'.$inventory.'件'];
            }
            //会员id
            $member_id = Session::get('member_id');
            $map['goods_id'] = $request->post('id');
            $map['attr'] = $request->post('attr');
            $map['limited_status'] = 0;
            $map['number'] = $request->post('num');
            $map['member_id'] = $member_id;   //会员id
            $map['price'] = (new ShopGoods())->where(['id' => $map['goods_id']])->value('price');
            //查找商品价格(已选属性按属性算)
            if ($request->post('attr_id')){   //选择了属性
                 $price = (new ShopSpecAttr())->where(['id' => $request->post('attr_id')])->field(['id','goods_id','price'])->find();
                 if ($price['goods_id'] == $map['goods_id']){
                     $map['price'] = $price['price'];
                 }
            }
            //是否是特价商品
            if ($request->post('special')){
                //查找特价商品价格
                $special_price = (new GroupGoods())->where(['goods_id' => $map['goods_id'] , 'status' => 1])->value('price');

                if (!$special_price) {return ['code'=>400,'message'=>'特价商品不存在'];}

                $map['price'] = $special_price;
                $map['limited_status'] = 1;
            }
            // 是否是本店铺
            $member = (new ShopGoods)->where(['id' => $map['goods_id']])->field('member_id,price')->find();
            if ($member['member_id'] == $member_id){return ['code'=>400,'message'=>'不能添加自己的商品'];}

            //查找购物车是否有相同收藏
            $model = new MemberShoppingCart();
            $status = $model->where(['member_id'=>$member_id,'price' => $map['price'], 'goods_id'=>$map['goods_id'],'attr'=>$map['attr']])->find();

            //有则合并
            if ($status){
                $res = $model->isUpdate(true)->where('id',$status['id'])->setInc('number',$map['number']);

                return $res?['code'=>200,'message'=>'添加成功']:['code'=>0,'message'=>'网络繁忙'];
                //没有则新增
            }else{
                $res = $model->isUpdate(false)->allowField(true)->save($map);

                return $res?['code'=>200,'message'=>'添加成功']:['code'=>0,'message'=>'网络繁忙'];
            }
        }
    }



    /*
     * 立即购买&加入购物车
     */
    public function confirm_order(Request $request)
    {
        if ($request->isPost()) {

            if (!Session::has('member_id')) {
                return ['code' => 401,'message' => '您未登录请先登录'];
            }

            //goods_id  attr[选好的商品属性] goods_attr_id属性id price[限时购价/商品市场单价] num limit_status
            $data = $request->post();

            //检测商品库存(无属性总库存)
            $inventory = (new ShopGoods())->where(['id' => $data['goods_id']])->value('inventory');

            if ($data['attr']){
                //有属性库存
                $attr_inventory = (new ShopSpecAttr())->where(['goods_id' => $data['goods_id'], 'attribute' => $data['attr']])->value('inventory');

                if (!$attr_inventory){
                    $inventory = 0;
                }else{
                    $inventory = $attr_inventory;
                }
            }

            if ($data['num'] > $inventory){
                return ['code' => 0,'message' => '库存不足,剩余'.$inventory.'件'];
            }

            //加入临时购物车
            $model = new TemporaryShoppingCart();
            // 是否是本店铺
            $member = (new ShopGoods)->where(['id' => $data['goods_id']])->field('member_id,price')->find();
            if ($member['member_id'] == Session::get('member_id')){return ['code'=>400,'message'=>'不能购买自己的商品'];}
            $map['member_id'] = Session::get('member_id');
            $map['goods_id'] = $data['goods_id'];
            $map['number'] = $data['num'];
            $map['limited_status'] = 0;
            $map['attr'] = $data['attr'];

            //单价
            $map['price'] = (new ShopGoods())->where(['id' => $map['goods_id']])->value('price');

            //查找商品价格(已选属性按属性算)
            if ($request->post('goods_attr_id')){   //选择了属性
                $price = (new ShopSpecAttr())->where(['id' => $request->post('goods_attr_id')])->field(['id','goods_id','price'])->find();
                if ($price['goods_id'] == $map['goods_id']){
                    $map['price'] = $price['price'];
                }
            }
            //是否是特价商品
            if ($request->post('special')){
                //查找特价商品价格
                $special_price = (new GroupGoods())->where(['goods_id' => $map['goods_id'] , 'status' => 1])->value('price');
                if (!$special_price) {return ['code'=>400,'message'=>'特价商品不存在'];}
                $map['price'] = $special_price;
                $map['limited_status'] = 1;
            }

            //有相同属性价格商品的物品合在一起
            $same = $model->where(['member_id' => Session::get('member_id'), 'goods_id' => $data['goods_id'], 'attr'  =>  $data['attr'], 'price' => $data['price']])->find();

            if ($same) {
                $return_id = $same['id'];
            } else {
                //存购物车
                $res = $model->isUpdate(false)->allowField(true)->save($map);
                $return_id = $model->id;
            }
            //成功返回购物车id
            return $return_id?['code'=>200,'message'=>$return_id ]:['code'=>0,'message'=>'网络繁忙,请重试'];
        }
    }


    /*
     * 立即抢购(检测是否符合条件)
     */
    public function buy_limit(Request $request)
    {
        if ($request->isPost()){
            $data = $request->post();

            if (!Session::has('member_id')) {
                return ['code' => 401,'message' => '您未登录请先登录'];
            }
            //检测限购时间是否过期

            // 是否是本店铺
            $member = ShopGoods::where(['id' => $data['goods_id']])->field('member_id,price')->find();

            if ($member['member_id'] == Session::get('member_id')){return ['code'=>400,'message'=>'不能购买自己的商品'];}


            $member_limita = Db::name('member_limited')->where(['member_id'=>Session::get('member_id'),'goods_id'=>$data['goods_id']])->value('number');


            $limit_info = db('rush_hour')->where('goods_id',$data['goods_id'])->find();
            if (!$limit_info){
                return ['code' => 402 , 'message' => '抢购商品不存在'];
            }

//            if ($limit_info['restrictions']<=$member_limita) {
//                return ['code' => 403 , 'message' => '超过每人抢购上限！此商品每人累计限购'.$limit_info['restrictions']."个"];
//            }
//
//            if ($limit_info['restrictions'] < $data['num']) {
//                return ['code' => 403 , 'message' => '超过每人抢购上限！此商品每人累计限购'.$limit_info['restrictions']."个"];
//            }


            //有未结束的活动
//            if ($limit_info->limitedType->end_time < time()){
//                return ['code' => 403 , 'message' => '活动已结束'];
//            }

            //检测购买的数量是否低于库存量
//            $sy = $limit_info['number'] - $limit_info['purchase_number'];

//            if ($sy < $data['num']){
//                return ['code' => 405 , 'message' => '库存不足,剩余'.$sy.'件'];
//            }

            $attr_id = Db::name('shop_spec_attr')->where(['goods_id'=>$data['goods_id'],'attribute'=>$data['attr']])->value('id');


            return ['code' => 200, 'message' => '符合条件','attr_id'=>$attr_id];

        }
    }


    /*
     * 删除购物车内的商品
     */
    public function cart_del(Request $request)
    {
        if ($request->isPost()){
            $id = $request->post('id');  //要删除的id或id串
            if ($id){
                $result = MemberShoppingCart::destroy($id);
                return $result?['code'=>200,'message'=>'删除成功']:['code'=>0,'message'=>'网络繁忙,请重试'];
            }
            return ['code'=>0,'message'=>'网络繁忙,请重试'];
        }
    }
    /*
     * 商品属性&数量选择
     */
    public function goods_attr(Request $request)
    {
        if ($request->isPost()){
            $attr_goods_id = $request->post('id');
            $member_cart_model = new MemberShoppingCart();
            //查询会员购物车商品
            $cart_goods = $member_cart_model
                ->where(['sun_member_shopping_cart.member_id'=>Session::get('member_id'),'sun_member_shopping_cart.goods_id'=>$attr_goods_id])
                ->with('shopGoods')
                ->find();
            //附加商品属性
            if ($cart_goods){
                $cart_goods->shopGoods->shopSpecAttr;
                if ($cart_goods->shopGoods->goods_attr != 'N;'){
                    $cart_goods->shopGoods->goods_attr = unserialize($cart_goods->shopGoods->goods_attr);
                }
            }
            return json($cart_goods);
        }
    }

    /*
     * 套餐属性选择
     */
    public function combo_attr(Request $request)
    {
        if ($request->isPost()){
            $goods_id = $request->post('id');  //商品id
            $model = new ShopGoods();
            $result = $model
                ->where(['id' => $goods_id])
                ->field('id,thumb_img,title,goods_attr')
                ->find();
            if ($result['goods_attr'] != 'N;'){
                $result['goods_attr'] = unserialize($result['goods_attr']);
            }
            return $result;
        }
    }
    /*
     * 更改新属性和数量
     */
    public function submit_new_attr(Request $request)
    {
        if ($request->isPost()){
            $data = $request->post();
            if ($data){
                $result = [];
                foreach ($data['cart_id'] as $key => $value){
                    $result[] = array_column($data,$key);
                }
                $keyArr = ['id','number','attr'];
                $newData = [];
                foreach ($result as $v){
                    $newData[] = array_combine($keyArr,$v);
                }
                //批量更改会员购物车商品
                $result = (new MemberShoppingCart())
                    ->allowField(true)
                    ->saveAll($newData);
                return $result;   //影响的商品数量
            }
        }
    }
}